package com.juyu.miliao.api.service;

import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.constant.PackageGroupConstant;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.ConfigApp;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.VerifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 包在线属性
 *
 * @author jh
 * 2018/11/22
 */
@Service
@Slf4j
public class PackageOnlineService {

    @Resource
    private ConfigAppService configAppService;

    /**
     * 获取包 在线属性
     *
     * @param request request
     * @return int EnumType.PACKAGE_OFFLINE
     */
    public int getOnline(HttpServletRequest request) {
        CommonHead commonHead = VerifyUtil.verifyCommonHead(request);
        return getOnline(commonHead);
    }

    /**
     * 获取包 在线属性
     *
     * @param commonHead commonHead
     * @return int EnumType.PACKAGE_OFFLINE
     */
    public int getOnline(CommonHead commonHead) {
        ConfigApp configApp;
        try {
            configApp = configAppService.getConfigApp(commonHead.getAppPackageId(), commonHead.getPhoneSystem());
        } catch (ConsumeRuntimeException e) {
            log.error("应用不存在,commonHead={}", commonHead.toString());
            return EnumType.ONLINE.state;
        }

        return getOnline(commonHead, configApp);
    }

    /**
     * // TODO: 2018/11/26 以后会使用渠道管理,线上线下去渠道管理查询
     * 获取包 在线属性
     * 1放在head里  1线上 2线下
     * 2旧的包管理 package_group
     * 3后台会做渠道管理,根据渠道查询线上线下以及商务数据等
     *
     * @param commonHead commonHead
     * @param configApp  configApp
     * @return int EnumType.PACKAGE_OFFLINE
     */
    public int getOnline(CommonHead commonHead, ConfigApp configApp) {
        if (configApp == null) {
            return EnumType.ONLINE.state;
        }
        //先判断新版线上线下,不存在再判断老版本设置,线下包用线下
        Integer online = commonHead.getOnline();
        if (online == null) {
            //老版本马甲包为线下,其余为线上
            if (configApp.getPackageGroup().equals(PackageGroupConstant.VEST)) {
                online = EnumType.VEST.state;
            } else {
                online = EnumType.ONLINE.state;
            }
        }
        return online;
    }

}
